package com.css.devops.monitor;

import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.springframework.http.HttpHeaders;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

public class JenkinsCSRFDisableHttpClient {

    public static void main(String[] args) throws Exception {
        String jenkinsUrl = "http://192.168.94.1:18080";
        String loginUrl = jenkinsUrl + "/j_spring_security_check";
        String crumbUrl = jenkinsUrl + "/crumbIssuer/api/json";
        String scriptUrl = jenkinsUrl + "/script";

        String username = "admin";
        String apiToken = "p@ssw0rd";

        String basicAuth = HttpHeaders.encodeBasicAuth(username, apiToken, StandardCharsets.UTF_8);
		HttpRequest request = HttpRequest.post(loginUrl).header(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
        HttpResponse response = request.execute();
        
        HttpRequest requestGet = HttpRequest.get(crumbUrl).header(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
        HttpResponse responseGet = requestGet.execute();
        
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(responseGet.body());
        String crumb = rootNode.path("crumb").asText();
        String crumbRequestField = rootNode.path("crumbRequestField").asText();
        
        Map<String,String> formMap = Maps.newConcurrentMap();
        String script = "hudson.security.csrf.GlobalCrumbIssuerConfiguration.DISABLE_CSRF_PROTECTION=true";
        formMap.put("script", script);
        formMap.put(crumbRequestField, crumb);
        response = HttpRequest.post(scriptUrl).header(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth).header(crumbRequestField, crumb).formStr(formMap).execute();
        System.out.println(response.getStatus());
    }
}




